package com.itheima.tlias.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.tlias.config.AliyunOssConfig;
import com.itheima.tlias.config.OssClient;
import com.itheima.tlias.util.ResultUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("upload")
public class UploadController {

    @Resource
    AliyunOssConfig ossConfig;

    @Resource
    OssClient ossClient;

    /**
     * MultipartFile -> Spring封装的用于接收文件的对象
     *
     * @param file
     * @return
     */
    @PostMapping
    public ResultUtil upload(MultipartFile file) throws IOException {
        //获取参数名
        log.info("name{}", file.getName());
        //获取实际上传的文件名
        log.info("OriginalFilename{}", file.getOriginalFilename());
        String filename = file.getOriginalFilename();
        String url = ossClient.upload(filename, file.getInputStream());
        return ResultUtil.success("上传成功",url);
        //拆分文件后缀(类型)
//        String originalFilename = file.getOriginalFilename();
//        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//        //阿里云oss访问路径
//        String endpoint = ossConfig.getEndpoint();
//        //填写Bucket名称
//        String bucketName = ossConfig.getBucketName();
        //加UUID防止文件名重复
//        String uuid = UUID.randomUUID().toString();
//        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
//        String objectName = uuid + suffix;
        //转移文件到阿里云oss
        // 创建OSSClient实例。要指定访问密钥
//        OSS ossClient = new OSSClientBuilder().build
//                (endpoint,ossConfig.getAccessKeyId(),ossConfig.getSecretAccessKey());
//        try {
//            ossClient.putObject(bucketName,objectName,file.getInputStream());
//            String url = ossConfig.getUrl()+objectName;
//            return ResultUtil.success(new StringBuilder(url));
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
    }
}
